
package com.multimedia.room.fragment;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.multimedia.room.BaseFragment;
import com.multimedia.room.CommandManager;
import com.multimedia.room.CommonUtil;
import com.multimedia.room.GroupInfo;
import com.multimedia.room.ISwitch;
import com.multimedia.room.MediaMessage;
import com.multimedia.room.R;
import com.multimedia.room.SwitchManager;

public class TeachBroadcastFragment extends BaseFragment implements ISwitch, OnCheckedChangeListener {
    private static final String TAG = "TeachBroadcastFragment";
    private RadioButton mchannelA, mchannelB, mchannelC, mchannelD,mchannelE,mchannelF,mchannelG,mchannelH;
    private RadioGroup mGroup;
    private Map<String, String> mMulticastChannelMap = new HashMap<String, String>();
    private String[] mMulticastChannel;
    private static MediaMessage mCurrentMessage;
    private String mSelectMulticastName;
    private TextView mMulticastView,mMulticastOverView;
    private SwitchManager mSwitchManager;
    private static String mGroupAddr;
    private static int mChannel = -1;
    private static String mFileName = null;
    private static String mAddr = null;
    private RelativeLayout mBroadcastRelayout;


    public static TeachBroadcastFragment newInstance(MediaMessage message) {
        TeachBroadcastFragment fragment = new TeachBroadcastFragment();
        mCurrentMessage = message;
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.d(TAG, "onCreateView()");
        View rootView = inflater.inflate(R.layout.teach_broadcast_layout, null);
        mBroadcastRelayout = (RelativeLayout) rootView.findViewById(R.id.broadcast_channel_layout);
        mMulticastView = (TextView) rootView.findViewById(R.id.broadcast_alert);
        mMulticastOverView = (TextView) rootView.findViewById(R.id.broadcast_over);
        mMulticastOverView.setVisibility(View.GONE);
        mGroup = (RadioGroup) rootView.findViewById(R.id.answer_group);
        mGroup.setVisibility(View.GONE);
        mGroup.setOnCheckedChangeListener(this);
        mchannelA = (RadioButton) rootView.findViewById(R.id.channel_a);
        mchannelB = (RadioButton) rootView.findViewById(R.id.channel_b);
        mchannelC = (RadioButton) rootView.findViewById(R.id.channel_c);
        mchannelD = (RadioButton) rootView.findViewById(R.id.channel_d);
        mchannelE = (RadioButton) rootView.findViewById(R.id.channel_e);
        mchannelF = (RadioButton) rootView.findViewById(R.id.channel_f);
        mchannelG = (RadioButton) rootView.findViewById(R.id.channel_g);
        mchannelH = (RadioButton) rootView.findViewById(R.id.channel_h);
//        parserTranslatorInfo(mCurrentMessage.getParams());
        mSwitchManager = SwitchManager.getInstance();
        mSwitchManager.registerMulticastSwitch(this);
        return rootView;
    }

    @Override
    public void onStart() {
        Log.d(TAG, "onStart()");
        super.onStart();
    }

    private void parserChannelInfo(String info) {
        String[] channelInfo = info.split(";");
        Log.d(TAG, "channelInfo "+channelInfo.toString());
        mMulticastChannel = new String[channelInfo.length];
        for (int i = 0; i < channelInfo.length; i++) {
        	mMulticastChannel[i] = channelInfo[i];
            String[] channelInfo_iner = mMulticastChannel[i].split(",");
            ((RadioButton) mGroup.getChildAt(i)).setText(channelInfo_iner[0]+"  "+channelInfo_iner[2]);
            ((RadioButton) mGroup.getChildAt(i)).setVisibility(View.VISIBLE);
//            mMulticastChannelMap.put(translator, GroupInfo.getGroupId("g"+GroupInfo.sAddressMap.get(translator)));
        }
    }

    private void updateTranslate() {
        for (int i = 0; i < mGroup.getChildCount(); i++) {
            ((RadioButton) mGroup.getChildAt(i)).setVisibility(View.GONE);
        }
        for (int i = 0; i < mMulticastChannel.length; i++) {
            String[] channelInfo = mMulticastChannel[i].split(",");
            ((RadioButton) mGroup.getChildAt(i)).setText(channelInfo[0]+"  "+channelInfo[2]);
            ((RadioButton) mGroup.getChildAt(i)).setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void switchOn(String params) {
        Log.d(TAG, "param === "+params);
        mBroadcastRelayout.setVisibility(View.VISIBLE);
        mMulticastOverView.setVisibility(View.GONE);
        mGroup.setEnabled(true);
        mchannelA.setEnabled(true);
        mchannelB.setEnabled(true);
        mchannelC.setEnabled(true);
        mchannelD.setEnabled(true);
        mchannelE.setEnabled(true);
        mchannelF.setEnabled(true);
        mchannelG.setEnabled(true);
        mchannelH.setEnabled(true);
        String tmp = decode(params);
        Log.d(TAG, "tmp === "+tmp);
        parserChannelInfo(tmp);
        if (isAdded()) {
            CommandManager.closeMic();
            mMulticastView.setText(R.string.select_channel);
            mGroup.setVisibility(View.VISIBLE);
            updateTranslate();
      }
    }

    @Override
    public void switchOff(String params) {
        Log.d(TAG, "multicast stop");
        CommandManager.multicastStop();
//        mGroup.setVisibility(View.GONE);
        mMulticastOverView.setVisibility(View.VISIBLE);
        mGroup.setEnabled(false);
        mchannelA.setEnabled(false);
        mchannelB.setEnabled(false);
        mchannelC.setEnabled(false);
        mchannelD.setEnabled(false);
        mchannelE.setEnabled(false);
        mchannelF.setEnabled(false);
        mchannelG.setEnabled(false);
        mchannelH.setEnabled(false);
    
//        mBroadcastRelayout.setVisibility(View.GONE);
    }

    @Override
    public void broadcastOn(String params) {

    }

    @Override
    public void brocadOff(String params) {

    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkId) {
        Log.d(TAG, "onCheckedChanged "+ checkId + mMulticastChannel.toString());
        switch (checkId) {
            case R.id.channel_a:
                mSelectMulticastName = mMulticastChannel[0];
                break;
            case R.id.channel_b:
                mSelectMulticastName = mMulticastChannel[1];
                break;
            case R.id.channel_c:
                mSelectMulticastName = mMulticastChannel[2];
                break;
            case R.id.channel_d:
                mSelectMulticastName = mMulticastChannel[3];
                break;
            case R.id.channel_e:
                mSelectMulticastName = mMulticastChannel[4];
                break;
            case R.id.channel_f:
                mSelectMulticastName = mMulticastChannel[5];
                break;
            case R.id.channel_g:
                mSelectMulticastName = mMulticastChannel[6];
                break;
            case R.id.channel_h:
                mSelectMulticastName = mMulticastChannel[7];
                break;
        }
        final String[] channelInfo = mSelectMulticastName.split(",");
        mChannel = Integer.parseInt(channelInfo[0]);
        mAddr = channelInfo[1];
        mFileName = channelInfo[2];
        Log.d(TAG, "addr "+mAddr +";"+ " channel "+mChannel + "; "+"filename "+mFileName);
        Log.d(TAG, "multicast play");
        CommandManager.multicastPlay(mAddr,mChannel);
        String receiveTranslate = getResources().getString(
                R.string.receive_multicast)
                + ":" + channelInfo[0]+"  "+channelInfo[2];
        mMulticastView.setText(receiveTranslate);
        CommandManager.closeMic();
    }
    @Override
	public void onDetach() {
		super.onDetach();
	}

    /*
     * 16进制数字字符集
     */
    private static String hexString = "0123456789ABCDEF";

    /*
     * 将字符串编码成16进制数字,适用于所有字符（包括中文）
     */
    public static String encode(String str) {
        // 根据默认编码获取字节数组
        byte[] bytes = str.getBytes();
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        // 将字节数组中每个字节拆解成2位16进制整数
        for (int i = 0; i < bytes.length; i++) {
            sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4));
            sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0));
        }
        return sb.toString();
    }

    /*
     * 将16进制数字解码成字符串,适用于所有字符（包括中文）
     */
    public static String decode(String bytes) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length() / 2);
        // 将每2位16进制整数组装成一个字节
        for (int i = 0; i < bytes.length(); i += 2)
            baos.write((hexString.indexOf(bytes.charAt(i)) << 4 | hexString.indexOf(bytes
                    .charAt(i + 1))));
        return new String(baos.toByteArray());
    }
}
